//
//  WKViewController.m
//  oc_demo
//
//  Created by haigui on 2021/8/31.
//

#import "WKViewController.h"
#import <WebKit/WebKit.h>
#import "MMTableView.h"
@interface WKViewController ()<WKNavigationDelegate, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) WKWebView *wkWebView;
@property (nonatomic, strong) MMTableView *tableView;
@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) UIScrollView *scrollView;
@end

@implementation WKViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    /**
     8903
     9332http://app.cps.com.cn/html/index.html#/article?id=9332
     */
    [self.view addSubview:self.tableView];

//    [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://app.cps.com.cn/html/index.html#/article?id=9332"]]];
}

#pragma mark - --------------代理方法--------------
#pragma mark -- UITableViewDelegate,UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 5;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        return _wkWebView.height;
    }
    return 40;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        static NSString *identifier = @"WebViewCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            [cell.contentView addSubview:self.scrollView];
        }
        return cell;
    }
    static NSString *identifier = @"UITableViewCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%ld", indexPath.row];
    return cell;
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
     }
     decisionHandler(WKNavigationActionPolicyAllow);
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
//    [webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        _wkWebView.frame= CGRectMake(0, 0, self.view.width, [result doubleValue]);//将WKWebView的高度设置为内容高度
//        _scrollView.height = [result doubleValue];
//        //刷新制定位置Cell
//        [_tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationNone];
//
//        NSLog(@"didFinishNavigation----%f",[result doubleValue]);
//    }];
    
//    @"Math.max(document.body.scrollHeight, document.body.offsetHeight, document.documentElement.clientHeight, document.documentElement.scrollHeight, document.documentElement.offsetHeight)"
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [webView evaluateJavaScript:@"document.body.scrollHeight"
//                      completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//                          if (!error) {
//                              double height = [result doubleValue];
//                              // do with the height
//
//                              dispatch_async(dispatch_get_main_queue(), ^{
//                                  _tableView.tableHeaderView.height = height;
//                                  webView.height = height;
//                                  [_tableView reloadData];
//
//                                  NSLog(@"didFinishNavigation----%f",height);
//                              });
//
////                              webView.height = height;
////                              _webScrollView.height = height;
////                              _webScrollView.contentSize = CGSizeMake(_webScrollView.width, height);
////                              [self refreshWebViewCell];
//
//                              NSLog(@"%f",height);
//                          }
//                      }];
//    });
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
    if (object == self.wkWebView.scrollView) {
        UIScrollView *sc = object;
        if ([keyPath isEqualToString:@"contentSize"]) {
            if (sc.contentSize.height != _scrollView.height) {
                _scrollView.height = sc.contentSize.height;
                _scrollView.contentSize = CGSizeMake(_scrollView.width, sc.contentSize.height);
                _wkWebView.height = sc.contentSize.height;
    //            _tableView.tableHeaderView.height = sc.contentSize.height;
                [_tableView reloadData];

                NSLog(@"observeValueForKeyPath----%f****%f",sc.contentSize.height,_wkWebView.height);
            }else{
//                NSLog(@"\n1:%f\n2:%f\n3:%f", _scrollView.contentOffset.y, _wkWebView.scrollView.contentOffset.y, _tableView.contentOffset.y);
                if (_wkWebView.scrollView.contentOffset.y>0) {
//                    [_tableView setContentOffset:CGPointM0ake(0, _wkWebView.scrollView.contentOffset.y)];
                }
            }
        }else if ([keyPath isEqualToString:@"estimatedProgress"]){
            CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
            if (newprogress) {
                _scrollView.height = sc.contentSize.height;
                _scrollView.contentSize = CGSizeMake(_scrollView.width, sc.contentSize.height);
                _wkWebView.height = sc.contentSize.height;
    //            _tableView.tableHeaderView.height = sc.contentSize.height;
                [_tableView reloadData];
            }
        }
    }
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
//    if ([scrollView isEqual:self.tableView]) {
//        CGFloat yOffSet = scrollView.contentOffset.y;
//        if (yOffSet <= 0) {
//            self.wkWebView.scrollView.scrollEnabled = YES;
//        }else{
//            self.wkWebView.scrollView.scrollEnabled = NO;
//        }
//    }
}
#pragma mark - --------------Getter方法--------------
- (WKWebView *)wkWebView {
    if (_wkWebView == nil) {
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width,user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript =[[WKUserScript alloc] initWithSource: jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc]init];
        config.userContentController = wkUController;
        _wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NavigationBarHeight)];
        _wkWebView.navigationDelegate = self;
        _wkWebView.allowsBackForwardNavigationGestures = YES;
        _wkWebView.scrollView.scrollEnabled = NO;
        
        [_wkWebView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
//        [_wkWebView.scrollView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return _wkWebView;
}
- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NavigationBarHeight)];
        _scrollView.scrollEnabled = NO;
        
        [_scrollView addSubview:self.wkWebView];
        [_wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://spe.cps.com.cn/2021zhsq/report-gkpw/web/viewer.html"]]];
    }
    return _scrollView;
}
- (MMTableView *)tableView{
    if (!_tableView) {
        _tableView = [[MMTableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-NavigationBarHeight) style:UITableViewStylePlain dataSource:self delegate:self];
//        _tableView.tableHeaderView = self.headerView;
    }
    return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, _tableView.width, 100)];
        
        [_headerView addSubview:self.wkWebView];
    }
    return _headerView;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
